package com.atguigu.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Author 马冰
 * @Date 2024/12/23 19:57
 * @注释
 */
@Controller
public class testResponseTest {

    @RequestMapping("/Response/text")
    @ResponseBody
    public String testResponseTest() {
        return "test";
    }

    /**
     * SpringMVC响应浏览器json格式的数据：
     * 1、使用@ResponseBody注解标记控制器方法
     * 2、将需要转换为json并响应到浏览器的Java对象作为控制器方法的返回值即可
     */
    @RequestMapping("/Response/map")
    @ResponseBody
    public Map<String, Object> testReponseJson() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username","admin");
        map.put("password","123456");
        map.put("age",18);
        return map;
    }

    @RequestMapping("/Response/html")
    public String testResponseHtml() {
        return "redirect:/first.html";
        //return "/first.html";
    }

    public ResponseEntity<byte[]> testFileDown() throws IOException {
        //获取下载的文件所对应的File对象
        File file = ResourceUtils.getFile("classpath:static/steve.png");
        //获取file所对应的字节输入流
        InputStream is = new FileInputStream(file);
        //创建一个存储文件字节的数组
        //is.available()获取字节输入流所对应文件的字节数
        byte[] bytes = new byte[is.available()];
        //将文件的字节读到bytes中
        is.read(bytes);

        MultiValueMap<String, String> headers = new HttpHeaders();
        //表示以附件的方式下载文件,attachment附件,filename设置下载的文件默认的文件名
        headers.add("Content-Disposition", "attachment; filename=steve.png");
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        is.close();
        return responseEntity;

    }

}
